package tingshu.servlet.album;

import lombok.SneakyThrows;
import tingshu.util.DBUtil;
import tingshu.util.Log;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

/**
 * 绑定音频
 * @author houdaiqin
 * @date 2022/07/20 14:26
 **/
@WebServlet("/studio/album/add.do")
public class AddJsonServlet extends HttpServlet {
    @Override
    @SneakyThrows
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserVO currentUser=null;
        HttpSession session=req.getSession(false);
        if (session!=null){
            currentUser=(UserVO) session.getAttribute("currentUser");
        }else{
            Log.println("用户未登录");
            return;
        }
        if (currentUser==null){
            Log.println("用户未登录");
            return;
        }
        int aid = Integer.parseInt(req.getParameter("aid"));
        String[] tidArr=req.getParameterValues("aid-tid");
        List<Integer> tidList=new ArrayList<>();
        for(String tid:tidArr){
            tidList.add(Integer.parseInt(tid));
        }

        //绑定音频就是在relatios表中插入一条记录
        String sqlFormat = "insert into relations (aid, tid) values %s";
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<tidList.size();i++){
            sb.append("(");
            sb.append(aid);
            sb.append(",");
            sb.append(tidList.get(i));
            sb.append(")");
            if (i!=tidList.size()-1) {
                sb.append(",");
            }
        }
        String sql=String.format(sqlFormat,sb.toString());
        Log.println("执行SQL"+sql);
        try(Connection c= DBUtil.connection()){
            try(PreparedStatement ps=c.prepareStatement(sql)){
                ps.executeUpdate();
            }
        }

        resp.sendRedirect("/studio/album/bind.html?aid="+aid);
//        resp.setCharacterEncoding("utf-8");
//        resp.setContentType("text/plain");
//        resp.getWriter().println("绑定成功");
    }
}